/*
 * @lc app=leetcode.cn id=704 lang=java
 *
 * [704] 二分查找
 */

// @lc code=start
class Solution {
    public int search(int[] nums, int target) {
        if(nums.length == 0) return -1;
        if(target < nums[0] || target > nums[nums.length - 1]) return -1;

        // 解法一： [left, right]
        // int left = 0, right = nums.length - 1;
        // while(left <= right) {
        //     int mid = left + (right - left) / 2;
        //     if(nums[mid] < target) {
        //         left = mid + 1;
        //     } else if(nums[mid] > target) {
        //         right = mid - 1;
        //     } else {
        //         return mid;
        //     }
        // }

        // 解法二： [left, right)
        int left = 0, right = nums.length;
        while(left < right) {
            int mid = left + (right - left) / 2;
            if(nums[mid] < target) {
                left = mid + 1;
            } else if(nums[mid] > target) {
                right = mid;
            } else {
                return mid;
            }
        }
        return -1;
    }
}
// @lc code=end

